package com.myownthemepark.s3vn;
import com.myownthemepark.s3vn.S3x;

import java.io.File;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

/**
 * Create local Subversion repository and store revision number in ZooKeeper.
 * 
 * @author alpha
 *
 */
public class MkRepo {
	public static void main(String[] args){
		String svnZooBucket = null;
		String svnZooPrefix = null;
		String svnZooZKAddr = null;
		String svnZooZKPrefix = null;
		String repoPattern = "s3vn-";
		String repoSuffix = ".mkrepo";
		File repoFd = null;
		S3vn s3vn = null;
		int ret;
		boolean failure = false;
		//Logger logger = Logger.getLogger(MkRepo.class);
		//logger.setLevel(Level.INFO);
		//BasicConfigurator.configure();
		
		try{		
			svnZooBucket = System.getenv("SVNZOO_BUCKET");
			svnZooPrefix = System.getenv("SVNZOO_PREFIX");
			svnZooZKAddr = System.getenv("SVNZOO_ZKADDR");
			svnZooZKPrefix = System.getenv("SVNZOO_ZKPREFIX");
			if (args.length > 0){
				repoFd = new File(args[0]);
			}else {
				repoFd = File.createTempFile(repoPattern, repoSuffix);
			}
			
			System.out.println("Temporary name is " + repoFd.getName());
			S3x.clear(svnZooBucket);
			
			s3vn = new S3vn(repoFd.getName(), svnZooBucket, svnZooPrefix, svnZooZKAddr, svnZooZKPrefix);
			s3vn.setProgName(repoFd.getName());
			
			s3vn.createZKSession();
			s3vn.createLocalRepo();
			s3vn.storeRepo();
			s3vn.endZKSession();
			ret = 0;
		}catch (Exception e){
			System.err.println(String.format("[Error]:\n%s\n\n[Stack trace]:", e.toString()));
			StackTraceElement[] ste = e.getStackTrace();
			int i;
			for (i = 0; i < ste.length; i++){
				System.out.println(ste[i].toString());
			}
			failure = true;
			ret = 1;
		}finally{
			try{
				if (!failure)
					s3vn.endZKSession();
			}catch (Exception e){
				System.err.println(String.format("[Error]:\n%s\n\n[Stack trace]:", e.toString()));
				StackTraceElement[] ste = e.getStackTrace();
				int i;
				for (i = 0; i < ste.length; i++){
					System.out.println(ste[i].toString());
				}
			}
		}
		return;
	}
}
